{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Homework 3\n",
    "\n",
    "Visualizing relationships between variables\n",
    "\n",
    "Allen Downey\n",
    "\n",
    "[MIT License](https://en.wikipedia.org/wiki/MIT_License)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "sns.set(style='white')\n",
    "\n",
    "from utils import decorate\n",
    "from thinkstats2 import Pmf, Cdf\n",
    "\n",
    "import thinkstats2\n",
    "import thinkplot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%time brfss = pd.read_hdf('brfss.hdf5', 'brfss')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brfss.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brfss.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brfss.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scatter plot\n",
    "\n",
    "Scatter plots are a good way to visualize the relationship between two variables, but it is surprising hard to make a good one.\n",
    "\n",
    "Here's a simple plot of height and weight."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "height = brfss['HTM4']\n",
    "weight = brfss['WTKG3']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(height, weight, 'o')\n",
    "\n",
    "plt.xlabel('Height in cm')\n",
    "plt.ylabel('Weight in kg');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The center of this plot is saturated, so it is not as dark as it should be, which means the rest of the plot is relatively darker than it should be.  It gives too much visual weight to the outliers and obscures the shape of the relationship.\n",
    "\n",
    "**Exercise:** Use keywords `alpha` and `markersize` to avoid saturation. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With transparency and smaller markers, you will be able to see that height and weight are discretized.\n",
    "\n",
    "**Exercise:** Use `np.random.normal` to add enough noise to height and weight so the vertical lines in the scatter plot are blurred out.  Create variables named `height_jitter` and `weight_jitter`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Linear regression\n",
    "\n",
    "We can use `scipy.stats` to find the linear least squares fit to weight as a function of height."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import linregress\n",
    "\n",
    "subset = brfss.dropna(subset=['WTKG3', 'HTM4'])\n",
    "xs = subset['HTM4']\n",
    "ys = subset['WTKG3']\n",
    "\n",
    "res = linregress(xs, ys)\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `LinregressResult` object contains the estimated parameters and a few other statistics.\n",
    "\n",
    "We can use the estimated `slope` and `intercept` to plot the line of best fit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# jitter the data\n",
    "height_jitter = height + np.random.normal(0, 2, size=len(height))\n",
    "weight_jitter = weight + np.random.normal(0, 2, size=len(weight))\n",
    "\n",
    "# make the scatter plot\n",
    "plt.plot(height_jitter, weight_jitter, 'o', markersize=1, alpha=0.02)\n",
    "plt.axis([140, 200, 0, 160])\n",
    "\n",
    "# plot the line of best fit\n",
    "fx = np.array([xs.min(), xs.max()])\n",
    "fy = res.intercept + res.slope * fx\n",
    "plt.plot(fx, fy, '-', alpha=0.5)\n",
    "\n",
    "# label the axes\n",
    "plt.xlabel('Height in cm')\n",
    "plt.ylabel('Weight in kg')\n",
    "plt.axis([140, 200, 0, 160]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Weight and age\n",
    "\n",
    "**Exercise:** Make a scatter plot of weight and age.  The variable `AGE` is discretized in 5-year intervals, so you might want to jitter it.  \n",
    "\n",
    "Adjust transparency and marker size to generate the best view of the relationship."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Use `linregress` to estimate the slope and intercept of the line of best fit for this data.\n",
    "\n",
    "Note: as in the previous example, use `dropna` to drop rows that contain NaN for either variable, and use the resulting subset to compute the arguments for `linregress`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Generate a plot that shows the estimated line and a scatter plot of the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Box and violin plots\n",
    "\n",
    "The Seaborn package, which is usually imported as `sns`, provides two functions used to show the distribution of one variable as a function of another variable.\n",
    "\n",
    "The following box plot shows the distribution of weight in each age category.  [Read the documentation](https://seaborn.pydata.org/generated/seaborn.boxplot.html) so you know what it means."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = brfss.dropna(subset=['AGE', 'WTKG3'])\n",
    "\n",
    "sns.boxplot(x='AGE', y='WTKG3', data=data, whis=10)\n",
    "\n",
    "sns.despine(left=True, bottom=True)\n",
    "plt.xlabel('Age in years')\n",
    "plt.ylabel('Weight in kg');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This figure makes the shape of the relationship clearer; average weight increases between ages 20 and 50, and then decreases.\n",
    "\n",
    "A violin plot is another way to show the same thing.  Again, [read the documentation](https://seaborn.pydata.org/generated/seaborn.violinplot.html) so you know what it means."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(x='AGE', y='WTKG3', data=data, inner=None)\n",
    "\n",
    "sns.despine(left=True, bottom=True)\n",
    "plt.xlabel('Age in years')\n",
    "plt.ylabel('Weight in kg');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Make a box plot that shows the distribution of weight as a function of income.  The variable `INCOME2` contains income codes with 8 levels.\n",
    "\n",
    "Use `dropna` to select the rows with valid income and weight information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Make a violin plot with the same variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plotting percentiles\n",
    "\n",
    "One more way to show the relationship between two variables is to break one variables into groups and plot percentiles of the other variable across groups.\n",
    "\n",
    "As a starting place, here's the median weight in each age group."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grouped = brfss.groupby('AGE')\n",
    "\n",
    "for name, group in grouped['WTKG3']:\n",
    "    print(name, group.median())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the other percentiles, we can use a `Cdf`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ps = [95, 75, 50, 25, 5]\n",
    "\n",
    "for name, group in grouped['WTKG3']:\n",
    "    percentiles = Cdf(group).Percentiles(ps)\n",
    "    print(name, percentiles)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now I'll collect those results in a list of arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = []\n",
    "for name, group in grouped['WTKG3']:\n",
    "    percentiles = Cdf(group).Percentiles(ps)\n",
    "    res.append(percentiles)\n",
    "    \n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the age groups, we can extract the \"keys\" from the groupby object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xs = grouped.groups.keys()\n",
    "xs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we want to loop through the columns of the list of arrays; to do that, we want to transpose it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rows = np.transpose(res)\n",
    "rows"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can plot the percentiles across the groups."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "width = [1,2,5,2,1]\n",
    "\n",
    "for i, qs in enumerate(rows):\n",
    "    plt.plot(xs, qs, label=ps[i], linewidth=width[i], color='C4')\n",
    "    \n",
    "decorate(xlabel='Age (years)',\n",
    "         ylabel='Weight (kg)')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In my opinion, this plot shows the shape of the relationship most clearly."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discretizing variables\n",
    "\n",
    "Box plot, violin plots, and percentile line plots don't work as well if the number of groups on the x-axis is too big.  For example, here's a box plot of weight versus height."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(x='HTM4', y='WTKG3', data=data, whis=10)\n",
    "\n",
    "sns.despine(left=True, bottom=True)\n",
    "plt.xlabel('Height in cm')\n",
    "plt.ylabel('Weight in kg');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This would look better and mean more if there were fewer height groups.  We can use `pd.cut` to put people into height groups where each group spans 10 cm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bins = np.arange(0, height.max(), 10)\n",
    "brfss['_HTMG10'] = pd.cut(brfss['HTM4'], bins=bins, labels=bins[:-1]).astype(float)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now here's what the plot looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(x='_HTMG10', y='WTKG3', data=brfss, whis=10)\n",
    "plt.xticks(rotation=30)\n",
    "\n",
    "sns.despine(left=True, bottom=True)\n",
    "plt.xlabel('Height in cm')\n",
    "plt.ylabel('Weight in kg');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Plot percentiles of weight versus these height groups."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Vegetables\n",
    "\n",
    "**Exercise:** The variable `_VEGESU1` contains the self-reported number of serving of vegetables each respondent eats per day.  Explore relationships between this variable and the others variables in the dataset, and design visualizations that show any relationship you find as clearly as possible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Correlation\n",
    "\n",
    "One way to compute correlations is the Pandas method `corr`, which returns a correlation matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "subset = brfss[['HTM4', 'WTKG3', 'AGE']]\n",
    "subset.corr()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercise:** Compute a correlation matrix for age, income, and vegetable servings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "subset = brfss[['AGE', 'INCOME2', '_VEGESU1']]\n",
    "subset.corr()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Correlation calibration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To calibrate your sense of correlation, let's look at scatter plots for fake data with different values of `rho`.\n",
    "\n",
    "The following function generates random normally-distributed data with approximately the given coefficient of correlation. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gen_corr(rho):\n",
    "    means = [0, 0]\n",
    "    covs = [[1, rho], [rho, 1]]\n",
    "    m = np.random.multivariate_normal(means, covs, 100)\n",
    "    return np.transpose(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This function makes a scatter plot and shows the actual value of `rho`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_scatter(rho, seed=1):\n",
    "    np.random.seed(seed)\n",
    "    xs, ys = gen_corr(rho)\n",
    "    rho = np.corrcoef(xs, ys)[0][1]\n",
    "\n",
    "    plt.plot(xs, ys, 'o', alpha=0.5)\n",
    "    plt.xlabel('x')\n",
    "    plt.ylabel('y')\n",
    "    ax = plt.gca()\n",
    "    label_rho(ax, rho)\n",
    "    \n",
    "    return xs, ys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def label_rho(ax, rho):\n",
    "    label = 'ρ = %0.2f' % rho\n",
    "    plt.text(0.05, 0.95, label, \n",
    "             horizontalalignment='left', \n",
    "             verticalalignment='top', \n",
    "             transform=ax.transAxes,\n",
    "             fontsize=12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following plots show what scatter plots look like with different values of `rho`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "res = []\n",
    "xs, ys = plot_scatter(0, seed=18)\n",
    "res.append((xs, ys))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xs, ys = plot_scatter(0.25, seed=18)\n",
    "res.append((xs, ys))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xs, ys = plot_scatter(0.5, seed=18)\n",
    "res.append((xs, ys))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xs, ys = plot_scatter(0.75, seed=18)\n",
    "res.append((xs, ys))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xs, ys = plot_scatter(0.95, seed=18)\n",
    "res.append((xs, ys))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here are all the plots side-by-side for comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(ncols=5, sharey=True, figsize=(15,3)) \n",
    "\n",
    "for ax, (xs, ys) in zip(axes, res):\n",
    "    ax.plot(xs, ys, 'o', alpha=0.5)\n",
    "    rho = np.corrcoef(xs, ys)[0][1]\n",
    "    label_rho(ax, rho)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nonlinear relationships\n",
    "\n",
    "Here an example that generates fake data with a nonlinear relationship."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(18)\n",
    "xs = np.linspace(-1, 1)\n",
    "ys = xs**2 + np.random.normal(0, 0.05, len(xs))\n",
    "\n",
    "plt.plot(xs, ys, 'o', alpha=0.5)\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This relationship is quite strong, in the sense that we can make a much better guess about `y` if we know `x` than if we don't.\n",
    "\n",
    "But if we compute correlations, they don't show the relationship."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame(dict(xs=xs, ys=ys))\n",
    "df.corr(method='pearson')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.corr(method='spearman')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.corr(method='kendall')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Correlation strength\n",
    "\n",
    "Here are two fake datasets showing hypothetical relationships between weight and age."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(18)\n",
    "xs = np.linspace(20, 50)\n",
    "ys1 = 75 + 0.02 * xs + np.random.normal(0, 0.15, len(xs))\n",
    "\n",
    "plt.plot(xs, ys1, 'o', alpha=0.5)\n",
    "plt.xlabel('Age in years')\n",
    "plt.ylabel('Weight in kg')\n",
    "\n",
    "rho = np.corrcoef(xs, ys1)[0][1]\n",
    "label_rho(plt.gca(), rho)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(18)\n",
    "xs = np.linspace(20, 50)\n",
    "ys2 = 65 + 0.2 * xs + np.random.normal(0, 3, len(xs))\n",
    "\n",
    "plt.plot(xs, ys2, 'o', alpha=0.5)\n",
    "plt.xlabel('Age in years')\n",
    "plt.ylabel('Weight in kg')\n",
    "\n",
    "rho = np.corrcoef(xs, ys2)[0][1]\n",
    "label_rho(plt.gca(), rho)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which relationship is stronger?\n",
    "\n",
    "It depends on what we mean.  Clearly, the first one has a higher coefficient of correlation.  In that world, knowing someone's age would allow you to make a better guess about their weight.\n",
    "\n",
    "But look more closely at the y-axis in the two plots.  How much weight do people gain per year in each of these hypothetical worlds?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import linregress\n",
    "        \n",
    "res = linregress(xs, ys1)\n",
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = linregress(xs, ys2)\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In fact, the slope for the second data set is almost 10 times higher."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following figures show the same data again, this time with the line of best fit and the estimated slope."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def label_slope(ax, slope):\n",
    "    label = 'm = %0.3f' % slope\n",
    "    plt.text(0.05, 0.95, label, \n",
    "             horizontalalignment='left', \n",
    "             verticalalignment='top', \n",
    "             transform=ax.transAxes,\n",
    "             fontsize=12)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = linregress(xs, ys1)\n",
    "fx = np.array([xs.min(), xs.max()])\n",
    "fy = res.intercept + res.slope * fx\n",
    "\n",
    "plt.plot(xs, ys1, 'o', alpha=0.5)\n",
    "plt.plot(fx, fy, '-', alpha=0.5)\n",
    "\n",
    "plt.xlabel('Age in years')\n",
    "plt.ylabel('Weight in kg')\n",
    "label_slope(plt.gca(), res.slope)\n",
    "\n",
    "plt.gca().get_ylim()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = linregress(xs, ys2)\n",
    "fx = np.array([xs.min(), xs.max()])\n",
    "fy = res.intercept + res.slope * fx\n",
    "\n",
    "plt.plot(xs, ys2, 'o', alpha=0.5)\n",
    "plt.plot(fx, fy, '-', alpha=0.5)\n",
    "\n",
    "plt.xlabel('Age in years')\n",
    "plt.ylabel('Weight in kg')\n",
    "label_slope(plt.gca(), res.slope)\n",
    "\n",
    "plt.gca().get_ylim()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The difference is not obvious from looking at the figure; you have to look carefully at the y-axis labels and the estimated slope.\n",
    "\n",
    "And you have to interpret the slope in context.  In the first case, people gain about 0.019 kg per year, which works out to less than half a pound per decade.  In the second case, they gain almost 4 pounds per decade.\n",
    "\n",
    "But remember that in the first case, the coefficient of correlation is substantially higher.\n",
    "\n",
    "**Exercise:** So, in which case is the relationship \"stronger\"?  Write a sentence or two below to summarize your thoughts."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
